package cuit.demo.service.impl;

import cuit.demo.Entity.Article;
import cuit.demo.Entity.Comment;
import cuit.demo.Entity.User;
import cuit.demo.service.MyService;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;

@Service
public class MyServiceImpl implements MyService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public User findUserById(int userId) {
        return entityManager.find(User.class, userId);
    }

    @Override
    public List<Article> findArticlesByUserId(int userId) {
        String queryStr = "SELECT a FROM Article a WHERE a.user_id = :userId";
        Query query = entityManager.createQuery(queryStr);
        query.setParameter("userId", userId);
        return query.getResultList();
    }

    @Override
    public List<Comment> findCommentsByArticleId(int articleId) {
        String queryStr = "SELECT c FROM Comment c WHERE c.article_id = :articleId";
        Query query = entityManager.createQuery(queryStr);
        query.setParameter("articleId", articleId);
        return query.getResultList();
    }

    @Override
    public List<Article> findAllArticles() {
        String queryStr = "SELECT a FROM Article a";
        Query query = entityManager.createQuery(queryStr);
        return query.getResultList();
    }
    @Transactional
    @Override
    public void saveUser(User newUser) {
        entityManager.persist(newUser);
    }

    @Override
    public Article findArticleById(int article_id) {
        return entityManager.find(Article.class, article_id);
    }

    @Transactional
    @Override
    public void saveArticle(Article newArticle) {
        entityManager.persist(newArticle);
    }

    @Transactional
    @Override
    public void deleteArticle(int articleId) {
        Article article = entityManager.find(Article.class, articleId);
        if (article!= null) {
            // 获取与文章关联的评论
            List<Comment> comments = findCommentsByArticleId(articleId);
            // 删除评论
            for (Comment comment : comments) {
                entityManager.remove(comment);
            }
            // 删除文章
            entityManager.remove(article);
        } else {
            throw new IllegalArgumentException("文章不存在，无法删除，文章 ID：" + articleId);
        }
    }

    @Transactional
    @Override
    public void saveComment(Comment newComment) {
        entityManager.persist(newComment);
    }

    @Override
    public Article findArticleByTitle(String title) {
        return entityManager.find(Article.class, title);
    }

    @Override
    public Comment findCommentById(int commentId) {
        return entityManager.find(Comment.class, commentId);
    }

    @Transactional
    @Override
    public void deleteComment(int commentId) {
        Comment comment = entityManager.find(Comment.class, commentId);
        if (comment != null) {
            entityManager.remove(comment);
        }
    }

    @Override
    public List<Article> findArticlesByArticleTitle(String title) {
        String queryStr = "SELECT a FROM Article a WHERE a.article_title = :title";
        Query query = entityManager.createQuery(queryStr);
        query.setParameter("title", title);
        // 返回匹配标题的文章列表
        return query.getResultList();
    }

    @Transactional
    @Override
    public boolean updateArticle(int articleId, String articleTitle, String articleText, String article_attachment, String attachment_name){
        // 使用EntityManager查找文章
        Article article = entityManager.find(Article.class, articleId);
        if (article != null) {
            // 更新文章属性
            article.setArticle_title(articleTitle); // 假设您在Article类中有此方法
            article.setArticle_text(articleText);
            article.setArticle_attachment(article_attachment);
            article.setAttachment_name(attachment_name);// 假设您在Article类中有此方法
            entityManager.merge(article); // 合并更新
            return true; // 返回成功
        }
        return false; // 返回失败
    }

    @Transactional
    @Override
    public void updateUser(User existingUser) {
        User user = entityManager.find(User.class,existingUser.getUserid());
        if(user!=null){
            user.setUserpwd(existingUser.getUserpwd());
            user.setUsername(existingUser.getUsername());
            user.setPhone(existingUser.getPhone());
            user.setEmail(existingUser.getEmail());
            user.setUsersex(existingUser.getUsersex());
            entityManager.merge(user);
        }
    }

    @Transactional
    @Override
    public List<Article> findArticlesByTitleOrAuthor(String keyword) {
        String wildCardKeyword = "%" + keyword + "%";

        // 构建查询语句，分别在文章标题和用户名字段进行模糊查询，并使用OR连接
        String queryStr = "SELECT a FROM Article a WHERE " +
                "LOWER(a.article_title) LIKE LOWER(:wildCardKeyword) OR " +
                "LOWER(a.articler) LIKE LOWER(:wildCardKeyword)";

        Query query = entityManager.createQuery(queryStr);
        query.setParameter("wildCardKeyword", wildCardKeyword);

        return query.getResultList();
    }

    public File getArticleAttachment(int articleId) {
        Article article = entityManager.find(Article.class, articleId);
        if (article!= null && article.getArticle_attachment()!= null) {
            try {
                return Paths.get(article.getArticle_attachment()).toFile();
            } catch (Exception e) {
                // 这里可以根据实际情况进行更详细的日志记录或错误处理
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
}